package cn.mesmile.juc.demo;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author zb
 * @date 2021/8/15 16:37
 * @Description
 */
public class AddAndSub2 {

    public static void main(String[] args) {
        Object object = new Object();
        AtomicInteger number = new AtomicInteger(0);

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                synchronized (object) {
                    while (number.get() > 0) {
                        try {
                            object.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    number.getAndIncrement();
                    System.out.println(Thread.currentThread().getName() + "当前值：" + number.get());
                    object.notifyAll();
                }
            }
        }, "A").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                synchronized (object) {
                    while (number.get() == 0) {
                        try {
                            object.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    number.set(number.get() - 1);
                    System.out.println(Thread.currentThread().getName() + "当前值：" + number.get());
                    object.notifyAll();
                }
            }
        }, "B").start();


        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                synchronized (object) {
                    while (number.get() > 0) {
                        try {
                            object.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    number.getAndIncrement();
                    System.out.println(Thread.currentThread().getName() + "当前值：" + number.get());
                    object.notifyAll();
                }
            }
        }, "C").start();


        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                synchronized (object) {
                    while (number.get() == 0) {
                        try {
                            object.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    number.set(number.get() - 1);
                    System.out.println(Thread.currentThread().getName() + "当前值：" + number.get());
                    object.notifyAll();
                }
            }
        }, "D").start();

    }


}
